package yc.star.friend.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import yc.star.common.constants.Constant;
import yc.star.common.domain.TableDataInfo;
import yc.star.common.utils.ThreadLocalUtil;
import yc.star.friend.domain.exam.dto.ExamQueryDTO;
import yc.star.friend.domain.exam.dto.ExamRankDTO;
import yc.star.friend.domain.exam.vo.ExamRankVO;
import yc.star.friend.domain.exam.vo.ExamVO;
import yc.star.friend.domain.user.vo.UserVO;
import yc.star.friend.manager.ExamCacheManager;
import yc.star.friend.manager.UserCacheManager;
import yc.star.friend.mapper.ExamMapper;
import yc.star.friend.mapper.UserExamMapper;
import yc.star.friend.service.IExamService;

import java.util.List;

@Service
public class ExamServiceImpl implements IExamService {

    @Autowired
    private ExamMapper examMapper;
    @Autowired
    private ExamCacheManager examCacheManager;
    @Autowired
    private UserExamMapper userExamMapper;
    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public List<ExamVO> list(ExamQueryDTO examQueryDTO) {
        PageHelper.startPage(examQueryDTO.getPageNum(),examQueryDTO.getPageSize());
        List<ExamVO> examVOList = examMapper.selectExamList(examQueryDTO);
        return examVOList;
    }

    @Override
    public TableDataInfo redisList(ExamQueryDTO examQueryDTO) {
        Long listSize = examCacheManager.getListSize(examQueryDTO.getType(),null);
        List<ExamVO> examVOList;
        if (listSize == null || listSize == 0) {
            // redis缓存列表中没有数据
            examVOList = list(examQueryDTO); // 从数据库中将竞赛列表信息查出
            examCacheManager.refreshCache(examQueryDTO.getType(),null); // 刷新缓存，将数据同步到缓存中
            listSize = new PageInfo<>(examVOList).getTotal();
        } else {
            // redis缓存中有数据,就直接从redis中查询
            examVOList = examCacheManager.getExamVOList(examQueryDTO,null);
            listSize = examCacheManager.getListSize(examQueryDTO.getType(),null);
        }
        if (CollectionUtil.isEmpty(examVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamVOList(examVOList);
        return TableDataInfo.success(examVOList,listSize);
    }

    @Override
    public String getFirstQuestion(Long examId) {
        Long examQuestionListSize = examCacheManager.getExamQuestionListSize(examId);
        if (examQuestionListSize == null || examQuestionListSize <= 0) {
            // 刷新缓存，将数据库中的数据同步到redis中
            examCacheManager.refreshExamQuestionCache(examId);
        }
        // 拿到该竞赛中的第一题的题目ID
        Long firstQuestionId = examCacheManager.getFirstQuestion(examId);
        return String.valueOf(firstQuestionId);
    }

    @Override
    public String preQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.preQuestion(examId, questionId).toString();
    }

    @Override
    public String nextQuestion(Long examId, Long questionId) {
        checkAndRefresh(examId);
        return examCacheManager.nextQuestion(examId, questionId).toString();
    }

    @Override
    public TableDataInfo rankList(ExamRankDTO examRankDTO) {
        Long total = examCacheManager.getRankListSize(examRankDTO.getExamId());
        List<ExamRankVO> examRankVOList;
        if (total == null || total <= 0) {
            // 从数据库中查
            PageHelper.startPage(examRankDTO.getPageNum(), examRankDTO.getPageSize());
            examRankVOList = userExamMapper.selectExamRankList(examRankDTO.getExamId());
            // 刷新缓存
            examCacheManager.refreshExamRankCache(examRankDTO.getExamId());
            total = new PageInfo<>(examRankVOList).getTotal();
        } else {
            examRankVOList = examCacheManager.getExamRankList(examRankDTO);
        }
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return TableDataInfo.empty();
        }
        assembleExamRankVOList(examRankVOList);
        return TableDataInfo.success(examRankVOList, total);
    }

    private void assembleExamVOList(List<ExamVO> examVOList) {
        // 从ThreadLocal中拿到userId
        Long userId = ThreadLocalUtil.get(Constant.USER_ID, Long.class);
        // 将用户报名的所有竞赛的id查出
        List<Long> userExamIdList = examCacheManager.getAllUserExamList(userId);
        if (CollectionUtil.isEmpty(userExamIdList)) {
            return;
        }
        for (ExamVO examVO : examVOList) {
            if (userExamIdList.contains(examVO.getExamId())) {
                examVO.setEnter(true);
            }
        }
    }

    private void assembleExamRankVOList(List<ExamRankVO> examRankVOList) {
        if (CollectionUtil.isEmpty(examRankVOList)) {
            return;
        }
        for (ExamRankVO examRankVO : examRankVOList) {
            Long userId = examRankVO.getUserId();
            UserVO user = userCacheManager.getUserById(userId);
            examRankVO.setNickName(user.getNickName());
        }
    }

    private void checkAndRefresh(Long examId) {
        Long listSize = examCacheManager.getExamQuestionListSize(examId);
        if (listSize == null || listSize <= 0) {
            examCacheManager.refreshExamQuestionCache(examId);
        }
    }

}